package ejb;

import entities.User;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Jesus
 */
@Stateless
public class UserBean implements UserBeanLocal {

    @PersistenceContext(unitName = "Tiendalia-ejbPU")
    private EntityManager em;

    @Override
    public User findByEmail(String email) {
        User res = null;
        Query query = em.createNamedQuery("User.findByEmail");
        query.setParameter("email", email.toLowerCase());
        try {
            res = (User) query.getSingleResult();
        } catch (NoResultException e) {
        }
        return res;
    }

    @Override
    public User insert(User user) {
        return update(user);
    }

    @Override
    public User update(User user) {
        return em.merge(user);
    }

    @Override
    public List<User> findAll() {
        Query query = em.createNamedQuery("User.findAll");
        return query.getResultList();
    }

    @Override
    public User findByCredentials(String email, String password) {
        User res = null;
        Query query = em.createNamedQuery("User.findByCredentials").
                setParameter("email", email).
                setParameter("password", password);
        try {
            res = (User) query.getSingleResult();
        } catch (NoResultException e) {
        }
        return res;
    }
}
